package demo;

import javax.persistence.*;

import org.mortbay.log.Log;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;

public class TrackDataAO {
	private static final Logger log = Logger.getLogger(MyTrackServlet.class
			.getName());
	EntityManager em;

	public TrackDataAO() {

	}

	public List<TrackData> getAll(String imei) {
		List<TrackData> list = new ArrayList<TrackData>();
		List<TrackData> raw = new ArrayList<TrackData>();
		em = EMF.get().createEntityManager();
		// Query q = em.createQuery("select from TrackData d");
		Query q = em.createQuery("select d from TrackData d where imei='"
				+ imei + "'");
		list = q.getResultList();
		em.close();
		Collections.sort(list);
		int size = list.size();
		TrackData tr;
		for (int i = 0; i < 20; i++) {
			tr = list.get(list.size() - i - 1);
			raw.add(tr);
		}

		return raw;
	}

	public List<MapData> getData(int max, String imei) {
		List<MapData> list = new ArrayList<MapData>();
		List<TrackData> h = new ArrayList<TrackData>();
		em = EMF.get().createEntityManager();
		// Query q = em.createQuery("select from TrackData d");
		Query q = em.createQuery("select d from TrackData d where imei='"
				+ imei + "'");
		List<TrackData> raw = q.getResultList();
		em.close();
		Collections.sort(raw);
		int size = raw.size();

		TrackData tr;
		if (size > 20) {
			for (int e = 0; e < 20; e++) {
				tr = raw.get(e);
				h.add(tr);
			}
		} else {
			for (int e = 0; e < size; e++) {
				tr = raw.get(e);
				h.add(tr);
			}
		}
		Collections.sort(h);
		int hsize = h.size();

		int len = max;
		if (max > hsize)
			len = hsize;
		for (int i = 0; i < len; i++) {

			MapData mData = new MapData();
			TrackData tData = h.get(len - i - 1);
			mData.setId(tData.getImei());
			long a = tData.getCurrent().getTime();
			Date b = new Date(a + (8 * 60 * 60 * 1000));
			mData.setDateTime(b);
			getLatLng(mData, tData.getGprmc());
			list.add(mData);
		}
		return list;
	}

	private boolean getLatLng(MapData mData, String gprmc) {
		String[] tokens = gprmc.split(",");
		if (tokens.length > 5) {
			String latStr = tokens[3];
			String lngStr = tokens[5];
			double lng = convert(lngStr);
			double lat = convert(latStr);
			mData.setLng(lng);
			mData.setLat(lat);
			return true;
		}
		return false;
	}

	private double convert(String str) {
		double d = -1;
		String[] tokens = str.split("\\.");

		String degree = tokens[0].substring(0, tokens[0].length() - 2);
		String min = tokens[0].substring(tokens[0].length() - 2) + "."
				+ tokens[1];
		d = Integer.parseInt(degree) + Double.parseDouble(min) / 60.0;

		return d;
	}

	public boolean add(String imei, String rmc) {
		TrackData data = new TrackData();
		em = EMF.get().createEntityManager();
		data.setImei(imei);
		data.setGprmc(rmc);
		data.setCurrent(new Date());
		em.persist(data);
		em.close();
		return true;
	}

/*	public long getCurr() {
		em = EMF.get().createEntityManager();
		Query q = em.createQuery(
				"select d.current from TrackData d order by d.current DESC")
				.setMaxResults(1);
		String qs = q.toString();
		Long gc = Long.parseLong(qs);
		em.close();
		return gc;
	}
	*/

	public Date getCurre() {
		em = EMF.get().createEntityManager();
		Query q = em.createQuery("select from TrackData d order by current DESC").setMaxResults(1);
		Date j = null;
		List<TrackData> raw = q.getResultList();
		
		em.close();
		if(raw!=null)
		{
			int rsize = raw.size();
		
			TrackData tData = raw.get(0);
			long a = tData.getCurrent().getTime();
			long c = 7 * 1000 * 60 * 60 * 24;
			long b = a - c;
			j = new Date(b);
			
		}
		return j;
	}
	
	public void DeleteData() {

		Date subdate = getCurre();
		
		em = EMF.get().createEntityManager();
		
		Query q = em.createQuery("delete from TrackData d where current <= :subdate");
		q.setParameter("subdate", subdate);
		int i = q.executeUpdate();
		System.out.println("Deleted: " + i);
		em.close();
	}

/*	public void delOneWeek() {

		// long subdate = getCurr() - (7 * 24 * 60 * 60);
		long DAY_IN_MS = 1000 * 60 * 60 * 24;
		Date subdate = new Date(getCurr() - (7 * DAY_IN_MS));

		em = EMF.get().createEntityManager();
		// em.getTransaction().begin();
		// Query q =
		// em.createQuery("select from TrackData d where d.current <= :subdate");
		// List l = q.getResultList();
		// em.remove(l);
		Query q = em
				.createQuery("delete from TrackData d where d.current <= :subdate");
		q.setParameter("subdate", subdate);
		int i = q.executeUpdate();
		System.out.println("Deleted: " + i);
		// em.getTransaction().commit();
		em.close();
	}
	*/

	public List<MapData> getAllData(int max) {
		List<MapData> list = new ArrayList<MapData>();
		List<TrackData> raw = new ArrayList<TrackData>();
		List<TrackData> h = new ArrayList<TrackData>();
		String num = null;

		TrackData tr;
		em = EMF.get().createEntityManager();
		Query j = em.createQuery("select distinct imei from TrackData d");
		String imeilist = j.getResultList().toString();
		em.close();
		if (imeilist.isEmpty() == false) {
			if (imeilist.contains(",") == true) {

				String[] ilist = imeilist.split(",");
				int siz = ilist.length;

				for (int i = 0; i < siz; i++) {
					if (i == 0) {
						num = ilist[i].substring(1);
					} else if (i == (siz - 1)) {
						num = ilist[i].substring(1, (ilist[i].length() - 1));
					} else {
						num = ilist[i].substring(1);
					}

					em = EMF.get().createEntityManager();

					Query get = em
							.createQuery("select from TrackData d WHERE imei='"
									+ num + "'");
					raw = get.getResultList();

					em.close();

					Collections.sort(raw);
					tr = raw.get(raw.size() - 1);
					h.add(tr);
				}

			}
		} else {
			num = imeilist.substring(1, (imeilist.length() - 1));
			em = EMF.get().createEntityManager();

			Query get = em.createQuery("select from TrackData d WHERE imei='"
					+ num + "'");
			raw = get.getResultList();

			em.close();

			Collections.sort(raw);
			tr = raw.get(raw.size() - 1);
			h.add(tr);

		}

		Collections.sort(h);
		int len = max;
		int size = h.size();
		if (max > size)
			len = size;

		for (int e = 0; e < len; e++) {
			MapData mData = new MapData();
			TrackData tData = h.get(len - e - 1);
			mData.setId(tData.getImei());
			long a = tData.getCurrent().getTime();
			Date b = new Date(a + (8 * 60 * 60 * 1000));
			mData.setDateTime(b);
			getLatLng(mData, tData.getGprmc());
			list.add(mData);
		}
		return list;
	}
}